package com.lagou.edu.mvcframework.interceptor;

import com.lagou.edu.mvcframework.pojo.Handler;
import com.lagou.edu.mvcframework.pojo.LogouModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class LagouHandlerExecutionChain {

    public Handler handler;

    public LagouHandlerExecutionChain(Handler handler) {
        this.handler = handler;
    }

    public Handler getHandler() {
        return handler;
    }

    public List<LagouHandlerInterceptor> lagouHandlerInterceptors;

    public List<LagouHandlerInterceptor> getLagouHandlerInterceptors() {
        if(lagouHandlerInterceptors==null||lagouHandlerInterceptors.isEmpty()){
             lagouHandlerInterceptors=new ArrayList<>();
        }
        return lagouHandlerInterceptors;
    }

    public void setLagouHandlerInterceptors(List<LagouHandlerInterceptor> lagouHandlerInterceptors) {
        this.lagouHandlerInterceptors = lagouHandlerInterceptors;
    }

    public LagouHandlerExecutionChain() {
    }

    public LagouHandlerExecutionChain(Handler handler, List<LagouHandlerInterceptor> lagouHandlerInterceptors) {
        this.handler = handler;
        this.lagouHandlerInterceptors = lagouHandlerInterceptors;
    }

    public void addInterceptor(LagouHandlerInterceptor handlerInterceptor) {
        getLagouHandlerInterceptors().add(handlerInterceptor);
    }

    public boolean applyPreHandle(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        for (int i = 0; i < getLagouHandlerInterceptors().size(); i++) {
            LagouHandlerInterceptor lagouHandlerInterceptor = getLagouHandlerInterceptors().get(i);
            if(!lagouHandlerInterceptor.preHandle(req,resp,handler)){
                return false;
            }
        }
        return true;
    }
    
    public void  applyPostHandle(HttpServletRequest req, HttpServletResponse resp, LogouModelAndView modelAndView) throws Exception {

        for (int i = getLagouHandlerInterceptors().size() - 1; i >= 0; i--) {
            LagouHandlerInterceptor lagouHandlerInterceptor = getLagouHandlerInterceptors().get(i);
            lagouHandlerInterceptor.postHandle(req,resp,handler,modelAndView);

        }
    }
}
